<div class="row tile">
    <div class="col-md-12 col-md-auto">
        <div class="ibox float-e-margins">
            <h3 class="ibox-title" langtag="page-hostedit"></h3>
            <div class="ibox-content">
                <form class="form-horizontal">
                    <input name="id" type="hidden" value="{{.h.Id}}">
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-clientid"></label>
                        <div class="col-sm-12">
                            <select class="form-control" name="client_id" data-live-search="true"></select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-remark"></label>
                        <div class="col-sm-12">
                            <input class="form-control" name="remark" placeholder="remark" type="text" value="{{.h.Remark}}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-host"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="info-suchashost" name="host" placeholder="" type="text" value="{{.h.Host}}">
                        </div>
                    </div>
                    <div class="form-group" id="scheme">
                        <label class="control-label font-bold" langtag="word-scheme"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" id="scheme_select" name="scheme">
                                <option {{if eq "all" .h.Scheme}}selected{{end}} value="all" langtag="word-all"></option>
                                <option {{if eq "http" .h.Scheme}}selected{{end}} value="http" langtag="word-http"></option>
                                <option {{if eq "https" .h.Scheme}}selected{{end}} value="https" langtag="word-https"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="flow_reset">
                        <label class="control-label font-bold" langtag="word-flowreset"></label>
                        <div class="col-sm-12">
                            <input name="flow_reset" type="checkbox" value="1">
                            <span class="help-block m-b-none" langtag="info-flowreset"></span>
                        </div>
                    </div>
                    {{if eq true .allow_flow_limit}}
                    <div class="form-group" id="flow_limit">
                        <label class="control-label font-bold" langtag="word-flowlimit"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="info-unrestricted" name="flow_limit" placeholder="" type="text" value="{{.h.Flow.FlowLimit}}">
                            <span class="help-block m-b-none" langtag="word-unit"></span>: M
                        </div>
                    </div>
                    {{end}}
                    {{if eq true .allow_time_limit}}
                    <div class="form-group" id="time_limit">
                        <label class="control-label font-bold" langtag="word-timelimit"></label>
                        <div class="col-sm-12">
                            <input class="form-control" id="time_limit_input" langtag="info-unrestricted" name="time_limit" placeholder="" type="text" value="{{.h.Flow.TimeLimit}}">
                            <span class="help-block m-b-none" langtag="info-timelimit"></span>
                        </div>
                    </div>
                    {{end}}
                    <div class="form-group" id="auto_https">
                        <label class="control-label font-bold" langtag="word-autohttps"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="auto_https">
                                <option {{if eq false .h.AutoHttps}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.AutoHttps}}selected{{end}}  value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="auto_cors">
                        <label class="control-label font-bold" langtag="word-autocors"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="auto_cors">
                                <option {{if eq false .h.AutoCORS}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.AutoCORS}}selected{{end}}  value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="compat_mode">
                        <label class="control-label font-bold" langtag="word-compatmode"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="compat_mode">
                                <option {{if eq false .h.CompatMode}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.CompatMode}}selected{{end}}  value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="https_just_proxy">
                        <label class="control-label font-bold" langtag="word-httpsjustproxy"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" id="https_just_proxy_select" name="https_just_proxy">
                                <option {{if eq false .h.HttpsJustProxy}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.HttpsJustProxy}}selected{{end}}  value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="proxy_protocol">
                        <label class="control-label font-bold" langtag="word-proxyprotocol"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="proxy_protocol">
                                <option value="0" {{if eq .h.Target.ProxyProtocol 0}}selected{{end}} langtag="word-disable"></option>
                                <option value="1" {{if eq .h.Target.ProxyProtocol 1}}selected{{end}} langtag="word-proxyprotocolv1"></option>
                                <option value="2" {{if eq .h.Target.ProxyProtocol 2}}selected{{end}} langtag="word-proxyprotocolv2"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="auto_ssl">
                        <label class="control-label font-bold" langtag="word-autossl"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="auto_ssl">
                                <option {{if eq false .h.AutoSSL}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.AutoSSL}}selected{{end}}  value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group" id="cert_file">
                        <label class="control-label font-bold" langtag="word-httpscert"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" id="pemText" langtag="info-pemtext" name="cert_file" placeholder="" rows="6" type="text">{{.h.CertFile}}</textarea>
                        </div>
                    </div>
                    <div class="form-group" id="key_file">
                        <label class="control-label font-bold" langtag="word-httpskey"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" id="pemKey" langtag="info-pemkey" name="key_file" placeholder="" rows="6" type="text">{{.h.KeyFile}}</textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-urlroute"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="info-unrestricted" name="location" placeholder="" type="text" value="{{.h.Location}}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-urlrewrite"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="info-urlrewrite" name="path_rewrite" placeholder="" type="text" value="{{.h.PathRewrite}}">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-redirecturl"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="info-redirecturl" name="redirect_url" placeholder="" type="text" value="{{.h.RedirectURL}}">
                        </div>
                    </div>
                    {{if eq true .allow_local_proxy}}
                    <div class="form-group" id="local_proxy">
                        <label class="control-label font-bold" langtag="word-proxytolocal"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="local_proxy">
                                <option {{if eq false .h.Target.LocalProxy}}selected{{end}} value="0" langtag="word-no"></option>
                                <option {{if eq true .h.Target.LocalProxy}}selected{{end}} value="1" langtag="word-yes"></option>
                            </select>
                        </div>
                    </div>
                    {{end}}
                    <div class="form-group" id="auth">
                        <label class="control-label font-bold" langtag="word-auth"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" langtag="info-suchasauth" name="auth" placeholder="" rows="4">{{.auth}}</textarea>
                            <span class="help-block m-b-none" langtag="info-targetauth"></span>
                        </div>
                    </div>
                    <div class="form-group" id="target_is_https">
                        <label class="control-label font-bold" langtag="word-targetishttps"></label>
                        <div class="col-sm-12">
                            <select class="form-control selectpicker" name="target_is_https">
                                <option {{if eq false .h.TargetIsHttps}}selected{{end}} value="0">HTTP</option>
                                <option {{if eq true .h.TargetIsHttps}}selected{{end}}  value="1">HTTPS</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label font-bold" langtag="word-target"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" langtag="info-suchasiplist" name="target" placeholder="" rows="4" type="text">{{.h.Target.TargetStr}}</textarea>
                            <span class="help-block m-b-none" langtag="info-targethost"></span>
                        </div>
                    </div>
                    <div class="form-group" id="header">
                        <label class="control-label font-bold" langtag="word-requestheader"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" name="header" placeholder="Cache-Control: no-cache" rows="4" type="text">{{.h.HeaderChange}}</textarea>
                            <span class="help-block m-b-none" langtag="info-header"></span>
                        </div>
                    </div>
                    <div class="form-group" id="resp_header">
                        <label class="control-label font-bold" langtag="word-responseheader"></label>
                        <div class="col-sm-12">
                            <textarea class="form-control" name="resp_header" placeholder="Strict-Transport-Security: max-age=31536000; includeSubDomains; preload" rows="4" type="text">{{.h.RespHeaderChange}}</textarea>
                            <span class="help-block m-b-none" langtag="info-header"></span>
                        </div>
                    </div>
                    <div class="form-group" id="hostchange">
                        <label class="control-label font-bold" langtag="word-requesthost"></label>
                        <div class="col-sm-12">
                            <input class="form-control" langtag="word-requesthost" name="hostchange" placeholder="" type="text" value="{{.h.HostChange}}" value="">
                        </div>
                    </div>
                    <div class="hr-line-dashed"></div>
                    <div class="form-group">
                        <div class="col-lg-12 col-sm-offset-2">
                            <button class="btn btn-secondary" onclick="goback()" type="button">
                                <i class="fa fa-fw fa-lg fa-window-close"></i> <span langtag="word-cancel"></span>
                            </button>
                            <button class="btn btn-success" onclick="submitform('edit', '{{.web_base_url}}/index/edithost', $('form').serializeArray())" type="button">
                                <i class="fa fa-fw fa-lg fa-save"></i> <span langtag="word-save"></span>
                            </button>
                            <button class="btn btn-warning" onclick="submitform('add', '{{.web_base_url}}/index/addhost', $('form').serializeArray())" type="button">
                                <i class="fa fa-fw fa-lg fa-check-circle"></i> <span langtag="word-add"></span>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        ["header", "resp_header", "redirect_url"].forEach(function(name){
            var el = document.getElementsByName(name)[0];
            if (el) {
                var div = document.createElement("div");
                div.innerHTML = el.value;
                div.innerHTML = div.textContent;
                el.value = div.textContent;
            }
        });

        if ($("#scheme_select").val() == "all" || $("#scheme_select").val() == "https") {
            $("#auto_https").css("display", "block")
            $("#https_just_proxy").css("display", "block")
            if ($("#https_just_proxy_select").val() == "1") {
                $("#auto_ssl").css("display", "none")
                $("#cert_file").css("display", "none")
                $("#key_file").css("display", "none")
            } else {
                $("#auto_ssl").css("display", "block")
                $("#cert_file").css("display", "block")
                $("#key_file").css("display", "block")
            }
        } else {
            $("#auto_ssl").css("display", "none")
            $("#cert_file").css("display", "none")
            $("#key_file").css("display", "none")
            $("#https_just_proxy").css("display", "none")
            $("#auto_https").css("display", "none")
        }

        const pemText = document.getElementById("pemText");
        const pemKey = document.getElementById("pemKey");

        // 阻止浏览器默认打开文件的行为
        document.addEventListener("dragover", function (event) {
            event.preventDefault();
        });

        pemText.addEventListener("drop", function (event) {
            event.preventDefault();
            const file = event.dataTransfer.files[0];
            const reader = new FileReader();
            reader.onload = function (e) {
                pemText.value = e.target.result;
                console.log("Upload pem")
                $('#edit_form').data('bootstrapValidator').updateStatus('pemText', 'NOT_VALIDATED');
                $('#edit_form').data('bootstrapValidator').validateField('pemText');
            }
            reader.readAsText(file);
        });

        pemKey.addEventListener("drop", function (event) {
            event.preventDefault();
            const file = event.dataTransfer.files[0];
            const reader = new FileReader();
            reader.onload = function (e) {
                pemKey.value = e.target.result;
                $('#edit_form').data('bootstrapValidator').updateStatus('pemKey', 'NOT_VALIDATED');
                $('#edit_form').data('bootstrapValidator').validateField('pemKey');
            }
            reader.readAsText(file);
        });

        $("#scheme_select").on("change", function () {
            if ($("#scheme_select").val() == "all" || $("#scheme_select").val() == "https") {
                $("#auto_https").css("display", "block")
                $("#https_just_proxy").css("display", "block")
                if ($("#https_just_proxy_select").val() == "1") {
                    $("#auto_ssl").css("display", "none")
                    $("#cert_file").css("display", "none")
                    $("#key_file").css("display", "none")
                } else {
                    $("#auto_ssl").css("display", "block")
                    $("#cert_file").css("display", "block")
                    $("#key_file").css("display", "block")
                }
            } else {
                $("#auto_ssl").css("display", "none")
                $("#cert_file").css("display", "none")
                $("#key_file").css("display", "none")
                $("#https_just_proxy").css("display", "none")
                $("#auto_https").css("display", "none")
            }
        })

        $("#https_just_proxy_select").on("change", function () {
            if ($("#https_just_proxy_select").val() == "1") {
                $("#auto_ssl").css("display", "none")
                $("#cert_file").css("display", "none")
                $("#key_file").css("display", "none")
            } else {
                $("#auto_ssl").css("display", "block")
                $("#cert_file").css("display", "block")
                $("#key_file").css("display", "block")
            }
        })
    });

    function getClientList() {
        const clientId = "{{if .h.Client.Id}}{{.h.Client.Id}}{{else}}{{.client_id}}{{end}}"; // 根据优先级选择
        $("select[name='client_id']").selectpicker({
            liveSearch: true,
            source: {
                data: function (callback, page) {
                    $.ajax({
                        method: 'POST',
                        url: "{{.web_base_url}}/client/list",
                        dataType: 'json',
                        data: { order: "asc", offset: 0, limit: 0 },
                        success: function(response) {
                            // 转换数据格式（必须包含 `value` 和 `text`）
                            const results = $.map(response.rows, function(item) {
                                let displayText = item.Remark ? item.Id + ' · ' + item.Remark : item.Id.toString();
                                return {
                                    value: item.Id,     // 选项的 value
                                    text: displayText,  // 选项的显示文本
                                    selected: item.Id == clientId // 默认选中
                                };
                            });
                            callback(results); // 返回给 selectpicker
                        },
                        error: function() {
                            callback([]); // 出错时返回空数组
                        }
                    });
                },
                search: function (callback, page, searchTerm) {
                    let data = { search: searchTerm, order: "asc", offset: 0, limit: 0 };
                    $.ajax({
                        method: 'POST',
                        url: "{{.web_base_url}}/client/list",
                        data: data,
                        dataType: 'json',
                        success: function(response) {
                            // 转换数据格式（必须包含 `value` 和 `text`）
                            const results = $.map(response.rows, function(item) {
                                let displayText = item.Remark ? item.Id + ' · ' + item.Remark : item.Id.toString();
                                return {
                                    value: item.Id,    // 选项的 value
                                    text: displayText, // 选项的显示文本
                                    selected: item.Id == clientId // 默认选中
                                };
                            });
                            callback(results); // 返回给 selectpicker
                        },
                        error: function() {
                            callback([]); // 出错时返回空数组
                        }
                    });
                }
            }
        });
    }

    function internationalized(current) {
        $.fn.selectpicker.defaults = {
            noneSelectedText: languages['content']['bootstrap-select']['noneSelectedText'][current],
            noneResultsText: languages['content']['bootstrap-select']['noneResultsText'][current]
        };
        getClientList();
    }
</script>